package com.turevskiy.android.whereiam;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.turevskiy.android.whereiam.R;

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.turevskiy.android.whereiam.MESSAGE";
    private Uri uri;
    private Handler mHandler;
    // UI handler codes.
    private static final int UPDATE_ADDRESS = 1;

    @Override protected void onStart() {
    	super.onStart();
    	
    	LocationManager locationManager =
                (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // Handler for updating text fields on the UI like the lat/long and address.
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case UPDATE_ADDRESS:
                    	Toast.makeText(getApplicationContext(), (String) msg.obj, Toast.LENGTH_LONG).show();
                        break;
                }
            }
        };
        
        if (!gpsEnabled) {
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("GPS is disabled. Go to location settings?")
        	       .setCancelable(false)
        	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   dialog.cancel();
        	               enableLocationSettings();
        	           }
        	       })
        	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
        	           public void onClick(DialogInterface dialog, int id) {
        	        	   dialog.cancel();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	alert.show();
          }    

    }
    
        private void enableLocationSettings() {
            Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(settingsIntent);
        }
        
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void doSmth(View view) {
    	
    	// Retrieve a list of location providers that have fine accuracy, no monetary cost, etc
    	Criteria criteria = new Criteria();
    	criteria.setAccuracy(Criteria.ACCURACY_FINE);
    	criteria.setCostAllowed(false);

    	LocationManager locationManager =
        (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	String providerName = locationManager.getBestProvider(criteria, true);

    	// If no suitable provider is found, null is returned.
    	if (providerName != null) {
    	   Location location = locationManager.getLastKnownLocation(providerName);
    	   
    	   String lat=Double.toString(location.getLatitude());
    	   String  lon=Double.toString(location.getLongitude());
    	   uri = Uri.parse("geo:" + lat + "," + lon);

           (new ReverseGeocodingTask(this)).execute(new Location[] {location});

	       	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	       	builder.setMessage("Your location is: " + uri.toString() + ". Show it on map?")
	       	       .setCancelable(true)
	       	       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	       	           public void onClick(DialogInterface dialog, int id) {
	       	                dialog.cancel();
	       	           }
	       	       })
		       	       .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
		       	           public void onClick(DialogInterface dialog, int id) {
		       	                dialog.cancel();
		       	 	       	// Map point based on address
		       	 	       	Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
		       	 	       	
		       	 	       	// Verify it resolves
		       	 	       	PackageManager packageManager = getPackageManager();
		       	 	       	List<ResolveInfo> activities = packageManager.queryIntentActivities(mapIntent, 0);
		       	 	       	boolean isIntentSafe = activities.size() > 0;
		       	 	

		       	 	       	// Start an activity if it's safe
		       	 	       	if (isIntentSafe) {
		       	 	       	    startActivity(mapIntent);
		       	 	       	}

		       	           }
	       	       });
	       	AlertDialog alert = builder.create();
	       	alert.show();

    	}
     }

 // AsyncTask encapsulating the reverse-geocoding API.  Since the geocoder API is blocked,
 // we do not want to invoke it from the UI thread.
 private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
     Context mContext;

     public ReverseGeocodingTask(Context context) {
         super();
         mContext = context;
     }

     @Override
     protected Void doInBackground(Location... params) {
         Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

         Location loc = params[0];
         List<Address> addresses = null;
         try {
             // Call the synchronous getFromLocation() method by passing in the lat/long values.
             addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
         } catch (IOException e) {
             e.printStackTrace();
             // Update UI field with the exception.
             Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget();
         }
         if (addresses != null && addresses.size() > 0) {
             Address address = addresses.get(0);
             // Format the first line of address (if available), city, and country name.
             String addressText = String.format("%s, %s, %s",
                     address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                     address.getLocality(),
                     address.getCountryName());
             // Update the UI via a message handler.
             Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
         }
         return null;
     }
 }
}

